#region Copyright (c) 2006-2009 Widgetsphere LLC, All Rights Reserved
//--------------------------------------------------------------------- *
//                          Widgetsphere  LLC                           *
//             Copyright (c) 2006-2009 All Rights reserved              *
//                                                                      *
//                                                                      *
//This file and its contents are protected by United States and         *
//International copyright laws.  Unauthorized reproduction and/or       *
//distribution of all or any portion of the code contained herein       *
//is strictly prohibited and will result in severe civil and criminal   *
//penalties.  Any violations of this copyright will be prosecuted       *
//to the fullest extent possible under law.                             *
//                                                                      *
//THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
//TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
//TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
//CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
//THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF WIDGETSPHERE LLC   *
//                                                                      *
//UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
//PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
//SUBSTANTIALLY THE SAME, FUNCTIONALITY AS ANY WIDGETSPHERE PRODUCT.    *
//                                                                      *
//THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
//CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF WIDGETSPHERE,      *
//INC.  THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO       *
//INSURE ITS CONFIDENTIALITY.                                           *
//                                                                      *
//THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
//PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
//EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
//THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
//SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                      *
//THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
//--------------------------------------------------------------------- *
#endregion
using System;
using Widgetsphere.Generator.Common.GeneratorFramework;
using System.Windows.Forms;
using Widgetsphere.Generator.Common.Util;
using System.Collections;
using System.Xml;
using Widgetsphere.Generator.ProjectItemGenerators;

namespace Widgetsphere.Generator.Models
{
	public class ColumnController : BaseModelObjectController
	{
		#region Member Variables

		#endregion

    #region Constructor

    protected internal ColumnController(IModelObject modelObject)
      : base(modelObject)
    {
    }

    #endregion

		#region BaseModelObjectController Members

		public override ModelObjectTreeNode Node
		{
			get
			{
				if(_node == null)
				{
					_node = new ColumnNode(this);
				}
				return _node;
			}
		}

		public override MenuCommand[] GetMenuCommands()
		{
			if (this.Node.Parent.Parent is TableNode)
			{
				MenuCommand menuDelete = new DefaultMenuCommand();
				menuDelete.Text = "Delete";
				menuDelete.Click += new EventHandler(DeleteMenuClick);

				MenuCommand menuSep = new DefaultMenuCommand();
				menuSep.Text = "-";

				MenuCommand menuCopy = new DefaultMenuCommand();
				menuCopy.Text = "Copy";
				menuCopy.Click += new EventHandler(CopyMenuClick);

				return new MenuCommand[] { menuDelete, menuSep, menuCopy };
			}
			else
			{
				return new MenuCommand[] {  };
			}
    }

    public override MessageCollection Verify()
    {
      try
      {
        MessageCollection retval = new MessageCollection();
        retval.AddRange(base.Verify());

        Column column = (Column)this.Object;

        //Check valid name
				if (!ValidationHelper.ValidDatabaseIdenitifer(column.DatabaseName))
					retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextInvalidIdentifier, column.Name), this);
				if (!ValidationHelper.ValidCodeIdenitifer(column.PascalName))
					retval.Add(MessageTypeConstants.Error, string.Format(ValidationHelper.ErrorTextInvalidIdentifier, column.Name), this);

        //Check valid name
        if ((column.CodeFacade != "") && !ValidationHelper.ValidDatabaseIdenitifer(column.CodeFacade))
          retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextInvalidCodeFacade, this);

				if (Globals.IsNumericType(column.Type))
				{
					if ((column.Min >= double.MinValue) && (column.Max >= double.MinValue))
					{
						if (column.Min > column.Max)
							retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextMinMaxValueMismatch, this);
					}
				}
				else //Non-numeric
				{
					//Neither should be set
					if ((column.Min >= double.MinValue) || (column.Max >= double.MinValue))
					{
						retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextMinMaxValueInvalidType, this);
					}
				}

        //Validate identity field
        if (column.Identity != IdentityTypeConstants.None)
        {
          //If this is an identity then must be of certain datatype
          switch (column.Type)
          {
            case System.Data.SqlDbType.TinyInt:
            case System.Data.SqlDbType.SmallInt:
            case System.Data.SqlDbType.Int:
						case System.Data.SqlDbType.BigInt:
						case System.Data.SqlDbType.UniqueIdentifier:
              break;
            default:
              retval.Add(MessageTypeConstants.Error, ValidationHelper.ErrorTextInvalidIdentityColumn, this);
              break;
          }
        }

        return retval;

      }
      catch (Exception ex)
      {
        throw;
      }

    }

    public override bool DeleteObject()
    {
      try
      {
        if(MessageBox.Show("Do you wish to delete the selected column?", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
          return false;

        ModelObjectTreeNode parentNode = (ModelObjectTreeNode)this.Node.Parent;				
        ReferenceCollection referenceCollection = (ReferenceCollection)parentNode.Object;
        ColumnCollection columnCollection = ((ModelRoot)this.Object.Root).Database.Columns;

        foreach(Reference reference in referenceCollection)
        {
          if(reference.Object == this.Object)
          {
						Column column = (Column)reference.Object;

						//Remove from any Table Components
						foreach(TableComponent tableComponent in ((Table)column.ParentTableRef.Object).ComponentList)
						{
							foreach (Reference r in tableComponent.Columns)
							{
								Column c = (Column)r.Object;
								if (c == column)
								{
									tableComponent.Columns.Remove(r);									
									break;
								}
							}
						}
						
						//Remove actual column
            columnCollection.Remove(column);

						//Remove column reference
						referenceCollection.Remove(reference);
            break;
          }
        }

        this.Node.Remove();
        this.Object.Root.Dirty = true;
				parentNode.Controller.Refresh();
				((ModelObjectTreeNode)parentNode.Parent).Refresh();
        return true;
      }
      catch(Exception ex)
      {
        throw;
      }

    }

    public override void Refresh()
    {
    }

		#endregion

		#region Menu Handlers

		private void DeleteMenuClick(object sender, System.EventArgs e)
		{
			this.DeleteObject();
		}

		private void CopyMenuClick(object sender, System.EventArgs e)
		{
			XmlDocument document = new XmlDocument();
			document.LoadXml("<a></a>");			
			((Column)this.Object).XmlAppend(document.DocumentElement);
			Clipboard.SetData("ws.model.column", document.OuterXml);
		}
		
		#endregion

	}
}